package com.lazypeople.application;

import com.lazypeople.domain.DownloadStatus;
import com.lazypeople.domain.DownloadTask;
import com.lazypeople.domain.ProgressListener;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskManager {
    // 单例实例 - 使用volatile确保多线程可见性
    private static volatile TaskManager instance;

    private final Map<String, DownloadTask> tasks = new ConcurrentHashMap<>();
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final List<TaskStatusListener> listeners = new ArrayList<>();
    private static final Logger logger = LoggerFactory.getLogger(TaskManager.class);

    // 私有构造函数防止外部实例化
    private TaskManager() {
        // 初始化代码（如有需要）
    }

    // 双重检查锁定实现单例
    public static TaskManager getInstance() {
        if (instance == null) {
            synchronized (TaskManager.class) {
                if (instance == null) {
                    instance = new TaskManager();
                }
            }
        }
        return instance;
    }

    // 添加下载任务并自动开始
    public String addTask(DownloadTask task) {
        String taskId = task.getTaskId();
        tasks.put(taskId, task);

        // 设置进度监听器
        task.addProgressListener(createProgressListener(task));

        // 提交任务到线程池执行
        executorService.submit(task);
        notifyStatusChanged(taskId, DownloadStatus.DOWNLOADING);
        return taskId;
    }

    // 暂停任务
    public boolean pauseTask(String taskId) {
        DownloadTask task = tasks.get(taskId);
        if (task != null) {
            task.pause();
            return true;
        }
        return false;
    }

    // 恢复任务
    public boolean resumeTask(String taskId) {
        DownloadTask task = tasks.get(taskId);
        if (task != null) {
            task.resume();
            executorService.submit(task);
            return true;
        }
        return false;
    }

    // 取消任务
    public boolean cancelTask(String taskId) {
        DownloadTask task = tasks.get(taskId);
        if (task != null) {
            task.cancel();
            tasks.remove(taskId);
            return true;
        }
        return false;
    }

    // 获取所有活跃任务
    public Map<String, DownloadTask> getAllTasks() {
        return new ConcurrentHashMap<>(tasks);
    }
    // 获取任务状态
    public DownloadStatus getTaskStatus(String taskId) {
        DownloadTask task = tasks.get(taskId);
        return task != null ? task.getStatus() : null;
    }

    // 添加任务状态监听器
    public void addTaskStatusListener(TaskStatusListener listener) {
        listeners.add(listener);
    }

    // 移除任务状态监听器
    public void removeTaskStatusListener(TaskStatusListener listener) {
        listeners.remove(listener);
    }

    // 通知进度变化
    private void notifyProgressChanged(String taskId, long downloaded, long total, float progress) {
        Platform.runLater(() -> {
            for (TaskStatusListener listener : listeners) {
                listener.onProgressUpdated(taskId, downloaded, total, progress);
            }
        });
    }

    // 通知状态变化
    private void notifyStatusChanged(String taskId, DownloadStatus status) {
        Platform.runLater(() -> {
            for (TaskStatusListener listener : listeners) {
                listener.onStatusUpdated(taskId, status);
            }
        });
    }

    // 任务状态监听器接口
    public interface TaskStatusListener {
        void onStatusUpdated(String taskId, DownloadStatus status);

        void onProgressUpdated(String taskId, long downloaded, long total, float progress);
    }

    // 关闭线程池
    public void shutdown() {
        executorService.shutdown();
    }

    // 通知进度变化
    private void notifyTaskProgressChanged(DownloadTask task, float progress, long downloadedBytes, long totalBytes) {
        Platform.runLater(() -> {
            String taskId = null;
            for (Map.Entry<String, DownloadTask> entry : tasks.entrySet()) {
                if (entry.getValue() == task) {
                    taskId = entry.getKey();
                    break;
                }
            }
            if (taskId != null) {
                notifyProgressChanged(taskId, downloadedBytes, totalBytes, progress / 100.0f);
            }
        });
    }

    // 通知状态变化
    private void notifyTaskStatusChanged(DownloadTask task, DownloadStatus status) {
        for (TaskStatusListener listener : listeners) {
            Platform.runLater(() -> {
                // 由于 DownloadTask 没有 getId() 方法，推测使用任务在 TaskManager 中的键作为 taskId
                String taskId = null;
                for (Map.Entry<String, DownloadTask> entry : tasks.entrySet()) {
                    if (entry.getValue() == task) {
                        taskId = entry.getKey();
                        break;
                    }
                }
                if (taskId != null) {
                    listener.onStatusUpdated(taskId, status);
                }
            });
        }
    }

    // 修复ProgressListener实现
    private ProgressListener createProgressListener(DownloadTask task) {
        return new ProgressListener() {
            @Override
            public void onProgressChanged(float progress, long downloadedBytes, long totalBytes) {
                logger.debug("TaskManager::createProgressListener->onProgressChanged");
                notifyTaskProgressChanged(task, progress, downloadedBytes, totalBytes);
            }

            @Override
            public void onStatusChanged(DownloadStatus status) {

                logger.debug("TaskManager::createProgressListener->onStatusChanged");
                notifyTaskStatusChanged(task, status);
            }
        };
    }
}